layout = window.layout || {};
var locate = window.location;
layout.protocol = locate.protocol;
var href = locate.href;
if (href.indexOf("debugger")!=-1) layout.debugger = true;
layout.desktop = layout;
layout.session = layout.session || {};
COMMON.DOM.addReady(function(){
    COMMON.AjaxModule.load("../x_desktop/res/framework/mootools/plugin/mBox.Notice.js", null, false);
    COMMON.AjaxModule.load("../x_desktop/res/framework/mootools/plugin/mBox.Tooltip.js", null, false);

    COMMON.setContentPath("../x_desktop");
    COMMON.AjaxModule.load("mwf", function(){
        MWF.defaultPath = "../x_desktop"+MWF.defaultPath;
        MWF.loadLP("zh-cn");

        MWF.require("MWF.widget.Mask", null, false);
        layout.mask = new MWF.widget.Mask({"style": "desktop"});
        layout.mask.load();

        MWF.require("MWF.xDesktop.Layout", function(){
            MWF.require("MWF.xDesktop.Authentication", null, false);

            (function(){
                layout.load = function(){
                    if (this.isAuthentication()){
                        //var preview = window.frameElement.retrieve("preview");
                        //layout.desktop = window.frameElement.ownerDocument.window.layout.desktop;
                        //

                        this.node = $("layout");
                        this.content = $(document.body);
                        this.path = "../x_component_process_Work/$Main/";
                        this.cssPath = "../x_component_process_Work/$Main/default/css.wcss";
                        this._loadCss();

                        MWF.require("MWF.xDesktop.MessageMobile", function(){
                            layout.message = new MWF.xDesktop.MessageMobile();
                            layout.message.load();
                        }.bind(this));

                        //MWF.xDesktop.requireApp("process.Work", "Actions.RestActions", null, false);
                        this.action = MWF.Actions.get("x_processplatform_assemble_surface");
                        //new MWF.xApplication.process.Work.Actions.RestActions();
                        //MWF.xDesktop.requireApp("process.Work", "lp."+MWF.language, null, false);
                        MWF.xApplication.process = MWF.xApplication.process || {};
                        MWF.xApplication.process.Work = MWF.xApplication.process.Work || {};
                        MWF.xDesktop.requireApp("process.Work", "lp."+MWF.language, {
                            "onRequestFailure": function(){
                                MWF.xDesktop.requireApp("process.Work", "lp.zh-cn", null, false);
                            }.bind(this),
                            "onSuccess": function(){}.bind(this)
                        }, false);

                        //this.lp = MWF.xApplication.process.Work.LP;

                        this.options = this.getIds();
                        this.loadWork(this.options);

                        //MWF.require("MWF.xApplication.process.Xform.Form", function(){
                        //    layout.appForm = new MWF.APPForm($("layout"), preview.data);
                        //    layout.appForm.load();
                        //});
                    }
                };
                layout.close = function(){
                    $(document.body).addEvent("click", function(){window.close();});
                };
                layout._loadCss = function(){
                    var key = encodeURIComponent(this.cssPath);
                    if (MWF.widget.css[key]){
                        this.css = MWF.widget.css[key];
                    }else{
                        var r = new Request.JSON({
                            url: this.cssPath,
                            secure: false,
                            async: false,
                            method: "get",
                            noCache: false,
                            onSuccess: function(responseJSON, responseText){
                                this.css = responseJSON;
                                MWF.widget.css[key] = responseJSON;
                            }.bind(this),
                            onError: function(text, error){
                                alert(error + text);
                            }
                        });
                        r.send();
                    }
                };

                layout.getIds = function(){

                    var href = window.location.href;
                    var qStr = href.substr(href.indexOf("?")+1, href.length);
                    var qDatas = qStr.split("&");
                    var obj = {};
                    qDatas.each(function(d){
                        var q = d.split("=");
                        obj[q[0].toLowerCase()] = q[1];
                    });

                    return obj;
                };

                layout.loadWork = function(options){
                    var id = options.workid || options.workcompletedid;
                    var application = options.app;
                    var form = options.form;
                    var method = (options.workid) ? "getJobByWorkAssignForm" : "getJobByWorkCompletedAssignForm";
                    if (method && id){
                        this.action[method](function(json){
                            if (this.mask) this.mask.hide();
                            this.parseData(json.data);
                            this.openWork();
                        }.bind(this), function(){
                            this.errorWork();
                        }, id, form);
                    }

                    //if (options.workid){
                    //    var method = "getJobByWorkAssignForm";
                    //    if (method && id){
                    //        this.action[method](function(json){
                    //            if (this.mask) this.mask.hide();
                    //            this.parseData(json.data);
                    //            this.openWork();
                    //        }.bind(this), function(){
                    //            this.errorWork();
                    //        }, id, application, form);
                    //    }
                    //}else if (options.workcompletedid){
                    //    id = options.workcompletedid;
                    //    this.action.getJobByWorkCompleted(function(json){
                    //        this.action.getForm(form, function(formJson){
                    //            json.data.form = formJson.data;
                    //            if (this.mask) this.mask.hide();
                    //            this.parseData(json.data);
                    //            this.openWork();
                    //        }.bind(this));
                    //    }.bind(this), function(){
                    //        this.errorWork();
                    //    }, id);
                    //}

                };

                layout.errorWork = function(){
                    if (this.mask) this.mask.hide();
                    this.node.set("text", "openError");
                };
                layout.getCurrentTaskData = function(data){
                    if (data.currentTaskIndex && data.currentTaskIndex != -1){
                        this.options.taskid = this.taskList[data.currentTaskIndex].id;
                        return this.taskList[data.currentTaskIndex];
                    }
                    if (this.taskList){
                        if (this.taskList.length==1){
                            this.options.taskid = this.taskList[0].id;
                            return this.taskList[0];
                        }
                    }

                    return null;
                };
                layout.parseData = function(data){
                 //   this.setTitle(this.options.title+"-"+data.work.title);

                    this.activity = data.activity;
                    this.data = data.data;
                    this.taskList = data.taskList;
                    this.currentTask = this.getCurrentTaskData(data);
                    this.taskList = data.taskList;
                    this.work = data.work;
                    this.workCompleted = data.workCompleted;
                    this.workLogList = data.workLogList;
                    this.attachmentList = data.attachmentList;
                    this.inheritedAttachmentList = data.inheritedAttachmentList;
                    this.control = data.control;
                    this.form = JSON.decode(MWF.decodeJsonString(data.form.data));
                };
                layout.openWork = function(){
                    MWF.xDesktop.requireApp("process.Xform", "Form", function(){
                        this.options.readonly = true;
                        this.appForm = new MWF.APPForm(this.node, this.form, {"readonly": this.options.readonly});
                        this.appForm.businessData = {
                            "data": this.data,
                            "taskList": this.taskList,
                            "work": this.work,
                            "workCompleted": this.workCompleted,
                            "control": this.control,
                            "activity": this.activity,
                            "task": this.currentTask,
                            "workLogList": this.workLogList,
                            "attachmentList": this.attachmentList,
                            "inheritedAttachmentList": this.inheritedAttachmentList,
                            "status": {
                                "readonly": (this.options.readonly) ? true : false
                            }
                        };
                        this.appForm.workAction = this.action;
                        this.appForm.app = this;
                        this.appForm.load();
                    }.bind(this))
                };

                layout.isAuthentication = function(){
                    layout.authentication = new MWF.xDesktop.Authentication({
                        "onLogin": layout.load.bind(layout)
                    });

                    var returnValue = true;
                    this.authentication.isAuthenticated(function(json){
                        this.user = json.data;
                    }.bind(this), function(){
                        this.authentication.loadLogin(this.node);
                        returnValue = false;
                    }.bind(this));
                    return returnValue;
                };
                //layout.getServiceAddress = function(callback){
                //    var host = layout.config.center.host || window.location.hostname;
                //    var port = layout.config.center.port;
                //    var uri = "";
                //    if (!port || port=="80"){
                //        uri = "http://"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }else{
                //        uri = "http://"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }
                //    var currenthost = window.location.hostname;
                //    uri = uri.replace(/{source}/g, currenthost);
                //    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";
                //    MWF.restful("get", uri, null, function(json){
                //        this.serviceAddressList = json.data;
                //        if (callback) callback();
                //    }.bind(this));
                //};
                //layout.getServiceAddress = function(callback){
                //    if (typeOf(layout.config.center)=="object"){
                //        this.getServiceAddressConfigObject(callback);
                //    }else if (typeOf(layout.config.center)=="array"){
                //        this.getServiceAddressConfigArray(callback);
                //    }
                //
                //};
                //layout.getServiceAddressConfigArray = function(callback) {
                //    var requests = [];
                //    layout.config.center.each(function(center){
                //        requests.push(
                //            this.getServiceAddressConfigObject(function(){
                //                requests.each(function(res){
                //                    if (res.isRunning()){res.cancel();}
                //                });
                //                if (callback) callback();
                //            }.bind(this), center)
                //        );
                //    }.bind(this));
                //};
                //layout.getServiceAddressConfigObject = function(callback, center){
                //    var centerConfig = center;
                //    if (!centerConfig) centerConfig = layout.config.center;
                //    var host = centerConfig.host || window.location.hostname;
                //    var port = centerConfig.port;
                //    var uri = "";
                //    if (!port || port=="80"){
                //        uri = "http://"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }else{
                //        uri = "http://"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }
                //    var currenthost = window.location.hostname;
                //    uri = uri.replace(/{source}/g, currenthost);
                //    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";
                //    return MWF.restful("get", uri, null, function(json){
                //        this.serviceAddressList = json.data;
                //        this.centerServer = center;
                //        if (callback) callback();
                //    }.bind(this));
                //};
                layout.confirm = function(type, e, title, text, width, height, ok, cancel, callback, mask, style){
                    MWF.require("MWF.xDesktop.Dialog", function(){
                        var size = this.content.getSize();
                        var x = 0;
                        var y = 0;

                        if (typeOf(e)=="element"){
                            var position = e.getPosition(this.content);
                            x = position.x;
                            y = position.y;
                        }else{
                            if (Browser.name=="firefox"){
                                x = parseFloat(e.event.clientX);
                                y = parseFloat(e.event.clientY);
                            }else{
                                x = parseFloat(e.event.x);
                                y = parseFloat(e.event.y);
                            }


                            //    if (!x || !y){
                            if (e.target){
                                var position = e.target.getPosition(this.content);
                                x = position.x;
                                y = position.y;
                            }
                            //    }
                        }

                        if (x+parseFloat(width)>size.x){
                            x = x-parseFloat(width);
                        }
                        if (x<0) x = 0;
                        if (y+parseFloat(height)>size.y){
                            y = y-parseFloat(height);
                        }
                        if (y<0) y = 0;

                        var ctext = "";
                        var chtml = "";
                        if (typeOf(text).toLowerCase()=="object"){
                            ctext = text.text;
                            chtml = text.html;
                        }else{
                            ctext = text;
                        }
                        var dlg = new MWF.xDesktop.Dialog({
                            "title": title,
                            "style": style || "flat",
                            "top": y,
                            "left": x-20,
                            "fromTop":y,
                            "fromLeft": x-20,
                            "width": width,
                            "height": height,
                            "text": ctext,
                            "html": chtml,
                            "container": this.content,
                            "maskNode": mask,
                            "buttonList": [
                                {
                                    "text": MWF.LP.process.button.ok,
                                    "action": ok
                                },
                                {
                                    "text": MWF.LP.process.button.cancel,
                                    "action": cancel
                                }
                            ]
                        });

                        switch (type.toLowerCase()){
                            case "success":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "error":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "info":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "warn":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            default:
                            //dlg.content.setStyle("background-image", "");
                        }
                        dlg.show();
                        if (callback) callback(dlg);
                    }.bind(this));
                };
                layout.notice = function(content, type, target, where, offset){
                    if (!where) where = {"x": "right", "y": "top"};
                    if (!target) target = this.content;
                    if (!type) type = "ok";
                    var noticeTarget = target || $(document.body);
                    var off = offset;
                    if (!off){
                        off = {
                            x: 10,
                            y: where.y.toString().toLowerCase()=="bottom" ? 10 : 10
                        };
                    }

                    new mBox.Notice({
                        type: type,
                        position: where,
                        move: false,
                        target: noticeTarget,
                        delayClose: (type=="error") ? 10000 : 5000,
                        offset: off,
                        content: content
                    });
                };

                layout.addEvent = function(){};

                MWF.getJSON("../x_desktop/res/config/config.json", function(config){
                    layout.config = config;


                    MWF.xDesktop.getServiceAddress(layout.config, function(service, center){
                        layout.serviceAddressList = service;
                        layout.centerServer = center;
                        layout.load();
                    }.bind(this));
                    //layout.getServiceAddress(function(){
                    //    layout.load();
                    //});
                });

            })();

        });
    });
});